<?php
/**
 * Created by PhpStorm.
 * User: Yixiao Chen
 * Date: 2015/6/25 0025
 * Time: 上午 9:35
 */

namespace Appstore\Model;


use Think\Model;

class AppstoreWatchModel extends Model
{
    protected $tableName = 'appstore_watch';


    /**订阅商品
     * @param $goods_id
     * @param int $auto 是否自动检测，如果设为0，则只做订阅操作；设为1，则会根据是否已订阅进行反向操作。
     * @return bool|int
     */
    public function watch($goods_id, $auto = 1,$uid=0)
    {
        $uid= $uid==0? get_uid():$uid;
        if($uid==0)
        {
            $this->error='未登录无法订阅';
            return false;
        }
        $map = array('uid' => $uid, 'goods_id' => $goods_id);
        $has = $this->checkWatched($goods_id,$uid);
        if ($has) {
            if ($auto == 0) {
                return 1;
            }
            $rs = $this->where($map)->delete();
            if ($rs) {
                M('AppstoreGoods')->where(array('id' => $goods_id))->setDec('watch_count');
                return 2;
            } else {
                $this->error = '数据库操作失败。';
                return false;
            }
        } else {
            $map['create_time'] = time();
            $rs = $this->add($map);
            if ($rs) {
                M('AppstoreGoods')->where(array('id' => $goods_id))->setInc('watch_count');
                $goods=M('AppstoreGoods')->find($goods_id);
                $self=query_user(array('nickname'),$uid);
                D('Common/Message')->sendMessage($goods['uid'],  '云市场商品被订阅通知', "{$self['nickname']}订阅了你的的商品《{$goods['title']}》动态，请再接再厉。", 'Appstore/Index/goodsDetail', array('id' => $goods_id), $uid, 2);

                return 1;
            } else {
                $this->error = '数据库操作失败。';
                return false;
            }
        }
    }


    /**检查是否已关注
     * @param $goods_id
     * @return mixed
     */
    public function checkWatched($goods_id,$uid=0)
    {
        $uid= $uid==0? get_uid():$uid;
        $map = array('uid' => $uid, 'goods_id' => $goods_id);
        return $this->where($map)->count();
    }

    /**获取已关注的列表
     * @param $goods_id
     * @return mixed
     */
    public function getWatched($goods_id)
    {
        $map = array('goods_id' => $goods_id);
        return $this->where($map)->select();
    }
}